package com.cmw.auntapp.ui;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;

import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cmw.auntapp.R;
import com.cmw.auntapp.adapter.ChatAdapter;
import com.cmw.auntapp.adapter.CommonFragmentPagerAdapter;
import com.cmw.auntapp.component.EmotionInputDetector;
import com.cmw.auntapp.component.im.NoScrollViewPager;
import com.cmw.auntapp.component.im.StateButton;
import com.cmw.auntapp.constant.Constant;
import com.cmw.auntapp.core.util.im.GlobalOnItemClickManagerUtils;
import com.cmw.auntapp.core.util.im.MediaManager;
import com.cmw.auntapp.core.util.im.MessageCenter;
import com.cmw.auntapp.fragment.ChatEmotionFragment;
import com.cmw.auntapp.fragment.ChatFunctionFragment;
import com.cmw.auntapp.model.im.MessageInfo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;


/**
 * 用户及时聊天页面
 * LQRWeChat: https://gitee.com/GitLqr/LQRWeChat/tree/master
 * 简书：https://www.jianshu.com/p/0db02677f91a
 * 汽泡参考：https://github.com/lguipeng/BubbleView
 * @Auth chengmingwei
 * @date 2021-08-23 07:36
 */
public class IMActivity extends BaseActivity {
    private static final String TAG = "IMActivity";

    @BindView(R.id.chat_list)
    RecyclerView chatList;

    @BindView(R.id.emotion_voice)
    ImageView emotionVoice;

    @BindView(R.id.edit_text)
    EditText editText;

    @BindView(R.id.voice_text)
    TextView voiceText;

    @BindView(R.id.emotion_button)
    ImageView emotionButton;

    @BindView(R.id.emotion_add)
    ImageView emotionAdd;

    @BindView(R.id.emotion_send)
    StateButton emotionSend;

    @BindView(R.id.viewpager)
    NoScrollViewPager viewPager;

    @BindView(R.id.emotion_layout)
    RelativeLayout emotionLayout;

    private EmotionInputDetector mDetector;

    private List<Fragment> fragments;

    private ChatEmotionFragment chatEmotionFragment;

    private ChatFunctionFragment chatFunctionFragment;

    private CommonFragmentPagerAdapter adapter;

    private ChatAdapter chatAdapter;

    private LinearLayoutManager layoutManager;

    private List<MessageInfo> messageInfos;

    // 录音相关
    int animationRes = 0;
    int res = 0;
    AnimationDrawable animationDrawable = null;
    private ImageView animView;


    @Override
    protected int getActivityLayout() {
        return R.layout.activity_im;
    }


    @Override
    void onInit(Bundle savedInstanceState) {
        EventBus.getDefault().register(this);
        initWidget();
        handleIncomeAction();
    }

    private void initWidget() {
        fragments = new ArrayList<>();
        chatEmotionFragment = new ChatEmotionFragment();
        chatFunctionFragment = new ChatFunctionFragment();
        fragments.add(chatEmotionFragment);
        fragments.add(chatFunctionFragment);
        adapter = new CommonFragmentPagerAdapter(getSupportFragmentManager(), fragments);
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(0);

        mDetector = EmotionInputDetector.with(this)
                .setEmotionView(emotionLayout).setViewPager(viewPager)
        .bindToContent(chatList).bindToEditText(editText)
        .bindToEmotionButton(emotionButton).bindToAddButton(emotionAdd)
        .bindToSendButton(emotionSend).bindToVoiceButton(emotionVoice)
        .bindToVoiceText(voiceText).build();

        GlobalOnItemClickManagerUtils globalOnItemClickListener = GlobalOnItemClickManagerUtils.getInstance(this);
        globalOnItemClickListener.attachToEditText(editText);
        initChatListWidget();
    }

    private void initChatListWidget() {
        chatAdapter = new ChatAdapter(messageInfos);
        layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        chatList.setLayoutManager(layoutManager);
        chatList.setAdapter(chatAdapter);
        // 添加滚动条监听事件
        chatList.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                switch (newState) {
                    case RecyclerView.SCROLL_STATE_IDLE: { //停止滚动 : 0
                        chatAdapter.handler.removeCallbacksAndMessages(null);
                        chatAdapter.notifyDataSetChanged();
                        break;
                    } case RecyclerView.SCROLL_STATE_DRAGGING: { // 正在被外部拖拽,一般为用户正在用手指滚动 : 1

                        break;
                    } case RecyclerView.SCROLL_STATE_SETTLING: { //自动滚动开始 : 2
                        chatAdapter.handler.removeCallbacksAndMessages(null);
                        mDetector.hideEmotionLayout(false);
                        mDetector.hideSoftInput();
                        break;
                    }
                }
            }
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) {
                // recyclerView : 当前滚动的view
                // dx : 水平滚动距离
                // dy : 垂直滚动距离
                super.onScrolled(recyclerView, dx, dy);
            }
        });
        chatAdapter.addOnItemClickListener(onItemClickListener);
        loadData();
    }

    /**
     * 加载消息数据
     */
    private void loadData() {
        messageInfos = new ArrayList<>();

        MessageInfo messageInfo = new MessageInfo();
        messageInfo.setContent("你好，欢迎使用Rance的聊天界面框架");
        messageInfo.setFileType(Constant.CHAT_FILE_TYPE_TEXT);
        messageInfo.setType(Constant.CHAT_ITEM_TYPE_LEFT);
        messageInfo.setHeader("http://img0.imgtn.bdimg.com/it/u=401967138,750679164&fm=26&gp=0.jpg");
        messageInfos.add(messageInfo);

        MessageInfo messageInfo1 = new MessageInfo();
        messageInfo1.setFilepath("http://www.trueme.net/bb_midi/welcome.wav");
        messageInfo1.setVoiceTime(3000);
        messageInfo1.setFileType(Constant.CHAT_FILE_TYPE_VOICE);
        messageInfo1.setType(Constant.CHAT_ITEM_TYPE_RIGHT);
        messageInfo1.setSendState(Constant.CHAT_ITEM_SEND_SUCCESS);
        messageInfo1.setHeader("https://pics4.baidu.com/feed/91ef76c6a7efce1bd235825f17d4f4d7b58f6593.png?token=df6ada79eb30329197c9ff74691b9c1e");
        messageInfos.add(messageInfo1);

        MessageInfo messageInfo2 = new MessageInfo();
        messageInfo2.setFilepath("https://pics7.baidu.com/feed/8694a4c27d1ed21b8d128a2715ebdacd53da3fa3.png?token=25d7ea7676b084e38265484c798706d3");
        messageInfo2.setFileType(Constant.CHAT_FILE_TYPE_IMAGE);
        messageInfo2.setType(Constant.CHAT_ITEM_TYPE_LEFT);
        messageInfo2.setHeader("https://pics4.baidu.com/feed/91ef76c6a7efce1bd235825f17d4f4d7b58f6593.png?token=df6ada79eb30329197c9ff74691b9c1e");
        messageInfos.add(messageInfo2);

        MessageInfo messageInfo3 = new MessageInfo();
        messageInfo3.setContent("[微笑][色][色][色]");
        messageInfo3.setFileType(Constant.CHAT_FILE_TYPE_TEXT);
        messageInfo3.setType(Constant.CHAT_ITEM_TYPE_RIGHT);
        messageInfo3.setSendState(Constant.CHAT_ITEM_SEND_ERROR);
        messageInfo3.setHeader("https://pics4.baidu.com/feed/91ef76c6a7efce1bd235825f17d4f4d7b58f6593.png?token=df6ada79eb30329197c9ff74691b9c1e");
        messageInfos.add(messageInfo3);

        chatAdapter.addAll(messageInfos);
    }

    /**
     * 播放语音
     * @param imageView
     * @param position
     */
    private void playVoice(ImageView imageView, int position) {
        if (animView != null) {
            animView.setImageResource(res);
            animView = null;
        }
        int type = messageInfos.get(position).getType();
        switch (type) {
            case 1 : {
                animationRes = R.drawable.voice_left;
                res = R.mipmap.icon_voice_left3;
                break;
            } case 2 : {
                animationRes = R.drawable.voice_right;
                res = R.mipmap.icon_voice_right3;
                break;
            }
        }
        animView = imageView;
        animView.setImageResource(animationRes);
        animationDrawable = (AnimationDrawable) imageView.getDrawable();
        animationDrawable.start();
        MediaManager.playSound(messageInfos.get(position).getFilepath(),
                (mediaPlayer) -> animView.setImageResource(res)
               );
    }

    private ChatAdapter.OnItemClickListener onItemClickListener = new ChatAdapter.OnItemClickListener() {
        @Override
        public void onHeaderClick(int position) {
            Log.i(TAG, "点击了用户图像...");
        }

        @Override
        public void onImageClick(View view, int position) {
            Log.i(TAG, "点击消息图片,暂未实现...");
        }

        @Override
        public void onVoiceClick(ImageView imageView, int position) {
            playVoice(imageView, position);
        }

        @Override
        public void onFileClick(View view, int position) {
            Log.i(TAG, "点击文件,暂未实现...");
        }

        @Override
        public void onLinkClick(View view, int position) {
            Log.i(TAG, "点击超链接,暂未实现...");
        }

        @Override
        public void onLongClickImage(View view, int position) {
            Log.i(TAG, "长按点击消息图片,暂未实现...");
        }

        @Override
        public void onLongClickText(View view, int position) {
            Log.i(TAG, "长按点击文字消息,暂未实现...");
        }

        @Override
        public void onLongClickItem(View view, int position) {
            Log.i(TAG, "长按点击Item消息,暂未实现...");
            playVoice((ImageView) view, position);
        }

        @Override
        public void onLongClickFile(View view, int position) {
            Log.i(TAG, "长按点击文件,暂未实现...");
        }

        @Override
        public void onLongClickLink(View view, int position) {
            Log.i(TAG, "长按点击超链接,暂未实现...");
        }
    };

    /**
     * 初始化接收消息处理器
     */
    private void handleIncomeAction() {
        Bundle bundle = getIntent().getExtras();
        if (bundle == null) {
            return;
        }
        MessageCenter.handleIncoming(bundle, getIntent().getType(), this);
    }

    /**
     *
     * @param messageInfo
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void MessageEventBus(final MessageInfo messageInfo) {

    }
}